package com.liusiqi.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: sql
 * @date: 2024/2/22
 * @Description:用来存储和遍历多个PropertyValue值
 * @version: 1.0
 */
public class MutablePropertyValues implements Iterable<PropertyValue>{

    private final List<PropertyValue> propertyValues;

    public MutablePropertyValues() {
        propertyValues = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValues) {
        this.propertyValues = propertyValues;
    }

    public List<PropertyValue> getPropertyValues() {
        return propertyValues;
    }

    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValues.iterator();
    }

    //获取元素
    public PropertyValue getPropertyValue(String name) {
        for (PropertyValue propertyValue : propertyValues) {
            if (propertyValue.getName().equals(name)) {
                return propertyValue;
            }
        }
        return null;
    }

    /**
     * 像集合中添加元素
     * @param propertyValue
     * @return
     */
    public MutablePropertyValues addPropertyValue(PropertyValue propertyValue) {
        for (int i = 0; i < propertyValues.size(); i++) {
            PropertyValue value = propertyValues.get(i);
            if (value.getName().equals(propertyValue.getName())) {
                propertyValues.set(i, propertyValue);
                return this;
            }
        }
        propertyValues.add(propertyValue);
        return this;
    }

    /**
     * 是否为空
     */
    public boolean isEmpty() {
        return propertyValues.isEmpty();
    }

    /**
     * 是否包含某元素
     * @param name
     * @return
     */
    public boolean contains(String name) {
        return getPropertyValue(name) != null;
    }

    @Override
    public String toString() {
        return "MutablePropertyValues{" +
                "propertyValues=" + propertyValues +
                '}';
    }
}
